package net.seehope.foodie.web.config.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import net.seehope.foodie.common.LoginType;
import net.seehope.foodie.properties.ProjectProperties;

@Component
public class FailureHandler extends SimpleUrlAuthenticationFailureHandler{
	
	@Autowired
	private ProjectProperties properties;
	
	@Autowired
	private ObjectMapper objectMapper;

	/**
	 * 失败时将异常的提示信息返回即可
	 */
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		if(properties.getBrowser().getLoginType().equals(LoginType.JSON)) {
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));
		}else {
			super.onAuthenticationFailure(request, response, exception);
		}
			
		
	}
	

}
